<template>
  <div>
    <a-modal :open='props.open' :width="props.modelInfo && props.modelInfo.width ? props.modelInfo.width : '900px'"
      :title="props.modelInfo && props.modelInfo.title ? props.modelInfo.title : 'Basic Modal'" @ok='handleOk'
      okText='保存' :confirmLoading='modelConfig.confirmLoading' :destroyOnClose='modelConfig.destroyOnClose'
      @cancel='handleCancel'>
      <template #footer>
        <a-button key='back' @click='handleCancel'>取消</a-button>
        <a-button key='submit' type='primary' :loading='loading' @click='handleOk'>保存</a-button>
      </template>
      <a-form ref='formRef' name='PartnerCategoryConfigForm' class='ant-advanced-search-form' :model='formState'
        @finish='onFinish' @finishFailed='onFinishFailed' :rules='rulesRef' :label-col='labelCol'
        :wrapper-col='wrapperCol'>
        <a-row :gutter='24'>
          <a-col :span='12'>
            <a-form-item :name="labelMap['categoryCode'].name" :label="labelMap['categoryCode'].label">
              <a-input v-model:value='formState.categoryCode'
                :placeholder="'请填写' + labelMap['categoryCode'].label"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item :name="labelMap['categoryName'].name" :label="labelMap['categoryName'].label">
              <a-input v-model:value='formState.categoryName'
                :placeholder="'请填写' + labelMap['categoryName'].label"></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter='24'>
          <a-col :span='12'>
            <a-form-item :name="labelMap['price'].name" :label="labelMap['price'].label">
              <a-input-number style="width: 100%;" v-model:value='formState.price'
                :placeholder="'请填写' + labelMap['price'].label"></a-input-number>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item :name="labelMap['originalPrice'].name" :label="labelMap['originalPrice'].label">
              <a-input-number style="width: 100%;" v-model:value='formState.originalPrice'
                :placeholder="'请填写' + labelMap['originalPrice'].label"></a-input-number>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter='24'>
          <a-col :span='12'>
            <a-form-item :name="labelMap['duration'].name" :label="labelMap['duration'].label">
              <a-input-number style="width: 100%;" v-model:value='formState.duration'
                :placeholder="'请填写' + labelMap['duration'].label" :precision="0" :step="1"></a-input-number>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item :name="labelMap['durationType'].name" :label="labelMap['durationType'].label">
              <a-select v-model:value="formState.durationType" :placeholder="'请填写' + labelMap['durationType'].label"
                style="width: 100%;">
                <a-select-option value="YEARS">年</a-select-option>
                <a-select-option value="MONTHS">月</a-select-option>
                <a-select-option value="DAYS">日</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>
<script lang='ts' setup>
  import { PartnerCategoryConfigDetail } from './partnerCategoryConfigDetailTs';
  import {
    getPartnerCategoryConfigDetail,
    addOrEditPartnerCategoryConfig,
  } from '@/api/userInfo/partnerCategoryConfig/partnerCategoryConfigTs';
  import { message, FormInstance } from 'ant-design-vue';
  import { ModelInfo } from '../partnerCategoryConfigListTs';

  const labelCol = ref({ span: 5 });
  const wrapperCol = ref({ span: 19 });

  let loading = ref<boolean>(false);

  const formRef = ref<FormInstance>();

  const labelMap = ref<any>(
    {
      categoryCode: { name: 'categoryCode', label: '类别编码' },
      categoryName: { name: 'categoryName', label: '类别名称' },
      price: { name: 'price', label: '实际价格' },
      originalPrice: { name: 'originalPrice', label: '原价' },
      duration: { name: 'duration', label: '购买时长' },
      durationType: { name: 'durationType', label: '时长类型' },
    });

  const rulesRef = reactive({
    categoryCode: [
      {
        required: true,
        message: '类别编码不能为空！',
      },
    ],
    categoryName: [
      {
        required: true,
        message: '类别名称不能为空！',
      },
    ],
    price: [
      {
        required: true,
        message: '实际价格不能为空！',
      },
    ],
    duration: [
      {
        required: true,
        message: '购买时长不能为空！',
      },
    ],
    durationType: [
      {
        required: true,
        message: '时长类型不能为空！',
      },
    ],
  });

  const modelConfig = {
    confirmLoading: true,
    destroyOnClose: true,
  };

  interface Props {
    open?: boolean;
    modelInfo?: ModelInfo;
  }
  const props = defineProps<Props>();

  let formState = ref<PartnerCategoryConfigDetail>({});


  const emit = defineEmits(['handleOk', 'handleCancel']);

  const handleOk = (): void => {
    loading.value = true;
    if (formRef.value) {
      formRef.value.validateFields().then(
        () => savePartnerCategoryConfigManager()).catch(() => {
          loading.value = false;
        });
    }
  };

  const handleCancel = (): void => {
    emit('handleCancel', false);
  };

  //保存合伙人类别配置表信息
  const savePartnerCategoryConfigManager = (): void => {
    let method = '';
    if (formState.value.id) {
      method = 'put';
    } else {
      method = 'post';
    }
    addOrEditPartnerCategoryConfig(method, formState.value)
      .then((res) => {
        if (res.code == '200') {
          message.success((res && res.message) || '保存成功！');
          formState.value = {};
          emit('handleOk', false);
        } else {
          message.error((res && res.message) || '保存失败！');
        }
      })
      .catch((error: any) => {
        message.error(error?.message || "查询失败！");
      }).finally(() => {
        loading.value = false;
      });
  }

  const onFinish = (values: any): void => {
    console.log('Success:', values);
  };

  const onFinishFailed = (errorInfo: any): void => {
    console.log('Failed:', errorInfo);
  };

  const init = (): void => {
    if (props.modelInfo) {
      if (props.modelInfo.id) {
        getPartnerCategoryConfigDetail(props.modelInfo.id)
          .then((res) => {
            if (res.code == '200') {
              formState.value = res.data;
              modelConfig.confirmLoading = false;
            } else {
              message.error((res && res.message) || '查询失败！');
            }
          })
          .catch((error: any) => {
            message.error(error?.message || "查询失败！");
          });
      } else {
        modelConfig.confirmLoading = false;
        formState.value = {
        };
      }
    }
  }

  watch(
    () => props.open,
    (newVal) => {
      if (newVal) {
        init();
      }
    },
    {
      immediate: true,
      deep: true,
    }
  );

  defineExpose({ handleOk, handleCancel });
</script>
<style lang='scss' scoped></style>